import React, { useRef } from "react";
import useStyles from "./style";

interface CatList {
  id: number;
  imageUrl: string;
}
const catList: CatList[] = [];
for (let i = 0; i < 10; i++) {
  catList.push({
    id: i,
    imageUrl: `https://placekitten.com/200/200?image=${i}`
  });
}

const CatFriends: React.FC = () => {
  const { nav, ul } = useStyles();

  const itemsRef = useRef<Map<number, HTMLLIElement>>();

  function scrollToId(itemId: number) {
    const map = getMap();
    const node = map.get(itemId);
    node?.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" });
  }

  function getMap() {
    if (!itemsRef.current) {
      itemsRef.current = new Map();
    }
    return itemsRef.current;
  }

  return (
    <>
      <nav className={nav}>
        <button onClick={() => scrollToId(0)}>Tom</button>
        <button onClick={() => scrollToId(5)}>Maru</button>
        <button onClick={() => scrollToId(9)}>Jellylorum</button>
      </nav>

      <ul className={ul}>
        {catList.map(cat => (
          <li
            key={cat.id}
            ref={node => {
              console.log(node);
              const map = getMap();
              if (node) {
                map.set(cat.id, node);
              } else {
                map.delete(cat.id);
              }
            }}
          >
            <img src={cat.imageUrl} alt={"Cat #" + cat.id} />
          </li>
        ))}
      </ul>
    </>
  );
};
export default CatFriends;
